package com.yvdedu.service;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Service;

import com.yvdedu.entity.Role;
import com.yvdedu.entity.User;
import com.yvdedu.factory.MySession;
import com.yvdedu.implement.UserImp;

@Service
public class UserService implements UserImp {

	private Session session;

	public User login(String userName, String pwd) {
		session = MySession.getSession();
		User user = null;
		String hql = "FROM User WHERE name = ? AND pwd = ?";
		try {
			user = (User) session.createQuery(hql).setString(0, userName)
					.setString(1, pwd).uniqueResult();

		} catch (Exception e) {
			return null;
		} finally {
			session.close();
		}
		return user;
	}

	public String reg(String userName, String pwd) {
		session = MySession.getSession();
		User user = new User();
		user.setName(userName);
		user.setPwd(pwd);
		Role role = (Role) session.get(Role.class, 5);
		user.setRole(role);
		try {
			Transaction tc = session.beginTransaction();
			session.save(user);
			tc.commit();
			return "success";
		} catch (Exception e) {
			return "defeat";
		} finally {
			session.close();
		}
	}

}
